import { Store } from './store'

interface HistoryCacheEntry {
  versionKey: string
  history: string
  updatedAt: number
}

const HISTORY_STORE_NAME = 'history-cache'
const HISTORY_KEY_PREFIX = 'history:'

const historyStore = new Store(HISTORY_STORE_NAME)

const normalizeVersionPart = (version?: string): string => {
  if (!version || version === '-' || version === 'undefined') {
    return ''
  }
  return version
}

export function buildHistoryVersionKey(workingVersion?: string, repositoryVersion?: string): string {
  const repo = normalizeVersionPart(repositoryVersion)
  const working = normalizeVersionPart(workingVersion)
  if (!repo && !working) {
    return ''
  }
  return `${repo}#${working}`
}

export async function getCachedHistory(filePath: string, versionKey?: string): Promise<string | undefined> {
  if (!versionKey) {
    return undefined
  }
  const cacheKey = `${HISTORY_KEY_PREFIX}${filePath}`
  const cacheEntry = await historyStore.get<HistoryCacheEntry>(cacheKey)
  if (cacheEntry && cacheEntry.versionKey === versionKey) {
    return cacheEntry.history
  }
  return undefined
}

export async function setCachedHistory(filePath: string, versionKey: string, history: string): Promise<void> {
  if (!versionKey) {
    return
  }
  const cacheKey = `${HISTORY_KEY_PREFIX}${filePath}`
  const entry: HistoryCacheEntry = {
    versionKey,
    history: history.trim(),
    updatedAt: Date.now()
  }
  await historyStore.set(cacheKey, entry)
}
